<template>
    <rx-layout>
        <div slot="left" width="220" showButton="true" :showModuleLeft="false" >
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="APP"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" border="false" foldbtn="false">
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" @click="add">{{$ti18('rxList.newBtn','新建')}}</a-button>
                        <a-button   icon="import" @click="doImport">{{$ti18('rxList.importBtn','导入')}}</a-button>
                        <a-button type="primary" v-if="selectedRowKeys.length > 0 " icon="delete" @click="delByRowsAndKeys(selectedRowKeys,selectedRows)">{{$ti18('rxList.delBtn','删除')}}</a-button>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}</span>
          </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.appCode','应用编码')">
                                    <a-input :placeholder="i18n('form.appCode','应用编码','input')" v-model="queryParam.Q_client_code__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.appName','应用名称')">
                                    <a-input :placeholder="i18n('form.appName','应用名称','input')" v-model="queryParam.Q_client_name__S_LK"/>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-system/system/core/sysApp/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','15','20','50']"
                    :idField="'appId'"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"  >
              <span slot="status" slot-scope="{ text, record }">
                <a-tag :color="statusMap[text].color">
                  <span>{{ statusMap[text].text }}</span>
                </a-tag>
              </span>
               <span slot="clientName" slot-scope="{ text, record }">
                 <span>{{ $i18(text,'应用名称') }}</span>
              </span>
               <span slot="appType" slot-scope="{ text, record }">
                <a-tag :color="appTypeMap[text].color">
                  <span>{{ appTypeMap[text].text }}</span>
                </a-tag>
              </span>
              <span slot="action" slot-scope="{text, record}" class="actionIcons">
                  <span v-if="editEnable" @click.stop="edit(record)">{{$ti18('rxList.editBtn','编辑')}}</span>
                  <span v-if="record.appType==1" @click.stop="preview(record)">{{$ti18('rxList.previews','预览')}}</span>
                   <span v-if="record.appType==1" @click.stop="doExport(record)">{{$ti18('rxList.exportBtn','导出')}}</span>
                  <span v-if="record.appType>0" @click.stop="delByIds([record.pkId])">{{$ti18('rxList.delBtn','删除')}}</span>
             </span>
                </rx-grid>
            </rx-fit>

            <a-drawer
                wrapClassName="grantDrawer"
                :title="drawerTitle"
                placement="right"
                :closable="true"
                @close="onClose"
                :visible="drawerVisible"
                :width="drawerWidth"
            >
                <template v-if="grantListShow">
                    <div style="padding-right: 24px;height: 100%;box-sizing: border-box;">
                        <rx-fit>
                            <rx-grid
                                ref="grantTable"
                                :bordered="isBorder"
                                :dataSource="grantData"
                                :allowRowSelect="true"
                                :multiSelect="true"
                                :columns="grantColumns"
                                :defaultPageSize="10"
                                data-field="result.data"
                                :pageSizeOptions="['10','30','40']"
                                id-field="appId"
                            >
                            </rx-grid>
                        </rx-fit>
                    </div>
                </template>
            </a-drawer>


        </div>
    </rx-layout>
</template>

<script>

import SysAppApi from '@/api/system/core/sysApp'
import SysAppEdit from './SysAppEdit'
import SysAppExport from "./SysAppExport";
import AppImport from '@/views/modules/system/core/AppImport';
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import {BaseList, RxLayout, RxFit, Util} from "@lowcode/jpaas-common-lib"
import userState  from "@/assets/js/userState";
import {mapState} from 'vuex';

export default {
    name: 'SysAppList',
    mixins: [BaseList,userState],
    components: {
        SysAppEdit,
        SysAppExport,
        RxLayout,
        RxFit,
        RxCategoryTreeeditor,
        AppImport
    },

    data() {
        return {
            labelCol: {
                xs: {span: 24},
                sm: {span: 5}
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 16}
            },
            mdl: {},
            // 高级搜索 展开/关闭
            advanced: false,
            //显示搜索
            showSearch: false,
            // 查询参数
            queryParam: {},
            treeId:'',
            // 表头
            columns: [
                {
                    title: '#',
                    type: 'indexColumn',
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'},
                    width: 40
                },
                {
                    title: this.i18n('form.appCode','应用编码'),
                    dataIndex: 'clientCode',
                    sorter:true,
                    sortField:"client_code_",
                    width: 100
                },
                {
                    title: this.i18n('form.appName','应用名称'),
                    dataIndex: 'clientName',
                    width: 120,
                    scopedSlots: {customRender: 'clientName'}
                },
                {
                    title: this.i18n('form.appType','应用类型'),
                    dataIndex: 'appType',
                    width: 100,
                    scopedSlots: {customRender: 'appType'}
                },
                {
                    title: this.i18n('form.status','状态'),
                    dataIndex: 'status',
                    width: 80,
                    scopedSlots: {customRender: 'status'}
                },
                {title: this.$ti18('rxForm.createTime','创建时间'), dataIndex: 'createTime', sorter: true, sortField: 'CREATE_TIME_', width: 120},
                {
                    title: this.$ti18('rxList.action','操作'),
                    dataIndex: 'action',
                    width: 80,
                    scopedSlots: {customRender: 'action'}
                }
            ],
            statusMap: {
                1: {color: 'green', text: this.i18n('form.enable','启用')},
                0: {color: 'gray', text: this.i18n('form.disable','禁用')},
            },
            appTypeMap:{
                0: {color: 'green', text: this.i18n('list.basicApp','后端应用')},
                1: {color: 'blue', text: this.i18n('list.developApp','开发应用')},
                2: {color: 'orange', text: this.i18n('list.systemApp','前端应用')},
            },
            component: SysAppEdit,
            comment: this.i18n('list.comment','应用管理'),
            //系统内置
            appType:'0',
            //后端应用
            showType_:"1",

            widthHeight: ['800px', '550px'],
            selectedRowKeys: [],
            selectedRows: [],
            addEnable: true,
            editEnable: true,
            removeEnable: true,
            drawerTitle: '',
            drawerWidth: '500',
            drawerVisible: false,
            grantListShow: false,
            grantData: [],
            grantParam: {},
            grantColumns: [
                {
                    title: this.i18n('form.appName','应用名称'),
                    width: 120,
                    dataIndex: 'clientName'
                },
                {
                    title: this.i18n('form.appCode','应用编码'),
                    dataIndex: 'clientCode',
                    width: 120,
                }
            ],
            statisticConfig: {
                type:"static_system",
                table:"SYS_APP",
                field:"CATEGORY_ID_",
                whereConf:[{name:"APP_TYPE_",type:"number",dateFormat:"",op:"in",value:"0,2"}]
            }
        }
    },
    created() {
        this.queryParam.Q_APP_TYPE__SN_IN="0,2";
    },

    methods: {
        delByRowsAndKeys(selectedRowKeys,selectedRows) {

            let self_ = this;
            this.$confirm({
                zIndex: 20000,
                title: self_.i18n('msa.deleteInfo','你确定要删除当前应用数据吗?'),
                content: self_.i18n('msa.propose','建议先备份数据；删除之后，相关的数据将无法恢复！'),
                okText: self_.i18n('list.deletion','确认删除'),
                cancelText: self_.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    self_.delById(selectedRowKeys).then(res => {
                        if (res.success && res.code == 200) {
                            self_.refreshGrid()
                        }
                        self_.selectedRowKeys = [];
                        self_.selectedRows = [];
                    })
                },
                onCancel() {
                }
            })
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"SysApp",key);
        },
        showGrantList(){
            this.drawerWidth = '500';
            this.drawerVisible = true;
            this.grantListShow = true;
            this.drawerTitle = this.i18n('list.myApp','授权给我的应用');
            var self_ = this;
            SysAppApi.getGrantList().then(res => {
                self_.grantData = res;
            })
        },
        onClose(e) {
            this.drawerVisible = false;
        },
        //一开始调用数据
        getListByParams(parameter) {
            return SysAppApi.query(parameter)
        },
        preview(record){
            let url;
            if(record.menuNavType=="1"){
                url=record.path + "/" +record.clientCode;
            }else {
                url= process.env.VUE_APP_ADMIN_FRONT+ "/" +record.clientCode +  "/";
            }
             window.open(url,"_blank");
        },
        // 删除
        delById(ids) {
            return SysAppApi.delByIds({ ids: ids.join(',') });
        },
        search() {
            this.$refs.table.loadData();
        },
        cancel() {
            this.$nextTick(() => {
                this.queryParam = {};
                this.queryParam.Q_APP_TYPE__SN_EQ=0;
                this.$nextTick(() => {
                    this.$refs[this.table].loadData();
                })
            })
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        handSelect(curRow) {
            var treeId = curRow.treeId
            let params={};
            if (treeId!="0"){
                params={Q_CATEGORY_ID__S_EQ: treeId};
            }else{
                params={Q_CATEGORY_ID__S_EQ: ''};
            }
            params.Q_APP_TYPE__SN_EQ=0;
            this.loadData(params)
            this.treeId=treeId;
        },
        //导入按钮事件方法
        doImport(){
            if(!this.treeId){
                this.$message.info(this.i18n('msa.importTips','请选择一个具体的应用分类！'));
                return ;
            }
            var self=this;
            Util.open(
                {
                    component: AppImport,
                    curVm: this,
                    widthHeight: ['1100px', '685px'],
                    title: this.i18n('appImport.import','应用导入'),
                    data: {
                        treeId:this.treeId,
                        callback: function (success,message) {
                            self.$message.info(message);
                            self.refreshGrid();
                        }
                    }
                },function (action) {
                });
        },
        //导出按钮事件方法
        doExport(curRow){
            let conf = {
                component: SysAppExport,
                widthHeight: ['480px', '300px'],
                title:this.i18n('export.exportApp','导出应用') + curRow.clientName,
                curVm:this,
                maxmin:false,
                zIndex:9969,
                data: {
                    appId: curRow.appId,
                    appName:curRow.clientName
                }
            };
            //弹出对话框
            const self_ = this;
            Util.open(conf,function (action,data) {
                if(action!='ok') return;
                //对话框确认后
                SysAppApi.doExport(data);
                this.$message.info(this.i18n('export.downloading','正在下载中...'));
            });
        }
    }
}
</script>
<style scoped>

</style>

